**Caculate Weighting
do "E:\yungyu\lottery_baby\do\set_environment.do"

capture log close
log using "$log\3.2.calculating_weights_single_age_`c(current_date)'.log" , replace
clear
set more off

foreach x in first { //single
foreach y in 5 30 {
		
	use "$wdata\project_lottery_fertility_b3a6_`x'_`y'k.dta", clear

	count if norm == -1
	local N = r(N)

	clear
	**Append 母體檔
	forv i = 96(1)101{
		append using "$wdata/population_`i'.dta"
	}

	gen population = 1

	gen win_age = age

	/*
	set seed 20230612
	gen random = rnormal()
	sort random
	keep if _n <= `N'
	*/

	ap using "$wdata\project_lottery_fertility_b3a6_`x'_`y'k.dta"
	keep if norm == -1 | norm == .
	recode population . = 0
	gen sample = population == 0

	gen count = 1
	collapse (sum)count, by(win_age married population)
	reshape wide count, i(win_age married) j(population)
	gen weight = count1/count0

	keep win_age married weight 

	save "$wdata\pop_weight_single_age_`x'_`y'.dta", replace

}
}

log close 
